import time

import requests
from bs4 import BeautifulSoup

baseUrl = "https://www.umei.cc/"
url = "https://www.umei.cc/gaoxiaotupian/"
headers = {
    "accept": "*/*",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
    "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
    "x-requested-with": "XMLHttpRequest"
}
res = requests.get(url, headers=headers)
res.encoding = "utf-8"
res.close()

# 获取分类页面下展示缩略图的href
page = BeautifulSoup(res.text, "html.parser")
pList = page.find("div", class_="taotu-main").find_all("p")
for p in pList:
    href = p.find("a").get("href")
    # 请求子页面获取源码
    child_page_res = requests.get(baseUrl + href)
    child_page_res.encoding = "utf-8"
    child_page_res.close()
    child_page = BeautifulSoup(child_page_res.text, "html.parser")
    # 定位图片所在元素
    img = child_page.find("div", class_="big-pic").find("a").find("img")
    src = img.get("src")
    # 下载图片
    img_src = requests.get(src)
    img_name = src.split("/")[-1] # src最后一个'/'后的名称
    with open("img/"+img_name,mode="wb") as f:
        f.write(img_src.content)
    print(img_name)
    f.close()
    time.sleep(1)


